using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using MonoCash.ObjectModel;
namespace MonoCash
{
    public partial class BalanceSheet : Form
    {
        
        public BalanceSheet()
        {
            InitializeComponent();
            dtAsOfDate.Value = DateTime.Today.AddDays(-1 * DateTime.Today.Day);
            PopulateTable();
        }

        private void PopulateTable()
        {
            DataTable bs = new DataTable("BalanceSheet");
            bs.Columns.Add("AccountID", Type.GetType("System.Int32"));
            bs.Columns.Add("AccountName", Type.GetType("System.String"));
            bs.Columns.Add("AccountBalance", Type.GetType("System.Decimal"));

            Account[] accounts = Account.Accounts.ToArray();
            foreach (Account account in accounts)
            {
                if (account.AccountingCategory.IsBalanceSheetCategory)
                {
                    DataRow row = bs.NewRow();
                    row["AccountID"] = account.ID;
                    row["AccountName"] = account.LongName;
                    row["AccountBalance"] = GetAmount(account);
                    bs.Rows.Add(row);
                }
            }
            dgvBalanceSheet.DataSource = bs;
        }
        private Decimal GetAmount(Account account)
        {
            decimal amount = 0;
            foreach (TransactionDetail td in account.TransactionDetails)
            {
                if (td.Date <= dtAsOfDate.Value)
                {
                    amount += td.Amount;
                }
            }
            //Recurse kids
            foreach (Account child in account.ChildAccounts)
            {
                amount += GetAmount(child);
            }

            return amount;
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            PopulateTable();
        }
    }
}